﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Web;
using NHibernate.Context;
using FluentNHibernate.Cfg;
using NHibernate.Cache;
using FluentNHibernate.Cfg.Db;
using NerdDinner.Data.Entities;

namespace NerdDinner.Data
{
    public class NHibernateSessionPerRequest : IHttpModule
    {
        private static readonly ISessionFactory _sessionFactory;

        static NHibernateSessionPerRequest()
        {
            _sessionFactory = CreateSessionFactory();
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest;
        }

        public static ISession GetCurrentSession()
        {
            return _sessionFactory.GetCurrentSession();
        }

        public void Dispose() { }

        private static void BeginRequest(object sender, EventArgs e)
        {
            ISession session = _sessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        private static void EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(_sessionFactory);

            if (session == null) return;

            try
            {
                session.Transaction.Commit();
            }
            catch (Exception)
            {
                session.Transaction.Rollback();
            }
            finally
            {
                session.Close();
                session.Dispose();
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            {

                return Fluently.Configure()
                .ExposeConfiguration(
                c => c.SetProperty("current_session_context_class", "web"))
                .Database(MsSqlConfiguration.MsSql2008
                .ConnectionString(
                @"Data Source=.\SQLEXPRESS;	Initial Catalog=WalkMe;Integrated Security=True")
                .Cache(c => c
                .UseQueryCache()
                .ProviderClass<HashtableCacheProvider>())
                .ShowSql())
                .Mappings(m => m
                .FluentMappings.AddFromAssemblyOf<Walk>())
                .BuildSessionFactory();

            }

            //.Database(MsSqlConfiguration.MsSql2005.ConnectionString(
            //   x => x.FromConnectionStringWithKey(connString)))
        }

    }
}
